package com.seckill.config;

import com.seckill.pojo.User;
import com.seckill.service.IUserService;
import com.seckill.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author levi
 * @version 1.0
 * @datetime 2021/8/25 20:57
 * @decription 用户形参处理器（用于登录验证）
 **/
@Component
@Slf4j
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    private String CLASS_NAME = "";

    UserArgumentResolver() {
        CLASS_NAME = this.getClass().getSimpleName();
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        //log.info("==> {},parameter:[{}]", CLASS_NAME, parameter);
        return clazz == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        /*HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        if (StringUtils.isEmpty(userTicket)) {
            //log.info("==> {},userTicket为空", CLASS_NAME);
            return null;
        }
        //log.info("==> {},userTicket:{}", CLASS_NAME, userTicket);
        return userService.getUserByCookie(userTicket, request, response);*/

        //登录用户放在ThreadLocal中
        return UserContext.getUser();
    }
}
